package de.tum.in.eist.poll.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.*;

public class LoginScreen implements ViewInterface {
	private boolean is_visible = false;
	
	// Widgets for this screen.
	private Label username_label = new Label("User:");
	private Label password_label = new Label("Password:");
	private TextBox username = new TextBox();
	private PasswordTextBox password = new PasswordTextBox();
	private Button submit = new Button("Login");
	
	public LoginScreen(final EIST_POLL controller) {
		submit.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				controller.login(username.getText(), password.getText());
			}
		});
		
		DOM.setElementAttribute(username.getElement(), "id", "username");
		DOM.setElementAttribute(password.getElement(), "id", "password");
		DOM.setElementAttribute(submit.getElement(), "id", "loginSubmit");
		KeyPressHandler keypress_handler = new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if(event.getCharCode() == KeyCodes.KEY_ENTER)
					submit.click();
			}
		};
		username.addKeyPressHandler(keypress_handler);
		password.addKeyPressHandler(keypress_handler);
	}

	@Override
	public void show() {
		is_visible = true;
		
		// Change the subtitle of the page.
		DOM.setInnerHTML(DOM.getElementById("subtitle"), "Login");
		
		// Clear the contents of the textfields.
		username.setText("");
		password.setText("");
		
		RootPanel r = RootPanel.get("content");
		r.add(username_label);
		r.add(username);
		r.add(password_label);
		r.add(password);
		r.add(submit);
		
		// We want the username textfield to have focus
		// when the login screen is shown.
		username.setFocus(true);
	}

	@Override
	public void hide() {
		is_visible = false;
		
		RootPanel r = RootPanel.get("content");
		r.remove(username_label);
		r.remove(username);
		r.remove(password_label);
		r.remove(password);
		r.remove(submit);
	}
	
	public boolean isVisible() {
		return is_visible;
	}
}
